/*
Copyright © 2021 NAME HERE <EMAIL ADDRESS>

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package cmd

import (
	"encoding/json"
	"fmt"
	"github.com/spf13/cobra"
	"io"
	"log"
	"net"
)

// netServeCmd represents the netServe command
var netServeCmd = &cobra.Command{
	Use:   "netServe [port]",
	Short: "A brief description of your command",
	Long: `A longer description that spans multiple lines and likely contains examples
and usage of using your command. For example:

Cobra is a CLI library for Go that empowers applications.
This application is a tool to generate the needed files
to quickly create a Cobra application.`,
	Run: func(cmd *cobra.Command, args []string) {
		fmt.Println("netServe called")
		netServe(args[0])
	},
}

func init() {
	rootCmd.AddCommand(netServeCmd)
}

type ProtoJson struct {
	Id int `json:"id"` // 发1代表获取这个端口的外网地址
}

func netServe(port string)  {
	if port == "" {
		port = "5213"
	}
	ln, err := net.Listen("tcp", ":" + port)
	if err != nil {
		log.Fatalln(err)
	}

	fmt.Println("netServer: ", port)

	rec := make([]byte, 0)
	for {
		conn, err := ln.Accept()
		fmt.Println("收到数据")
		if err != nil {
			log.Println(err)
			continue
		}
		fmt.Println("获取的net RemoteAddr: ", conn.RemoteAddr().String())
		fmt.Println("loacl addr: " , conn.LocalAddr().String())

		// 第一次读取消息字节数
		data := make([]byte, 1024 * 1024)
		read, err := conn.Read(data)
		if err != nil || err == io.EOF {
			go workServe(rec)
			continue
		}

		rec = append(rec, data[:read]...)
	}


}

func workServe(rec []byte)  {
	j := &ProtoJson{}
	err := json.Unmarshal(rec, j)
	if err != nil {
		fmt.Println("序列化失败")
		return
	}

	if j.Id == 1 {

	}
}
